package com.yyg.wiki.service;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yyg.wiki.domain.Content;
import com.yyg.wiki.domain.Doc;
import com.yyg.wiki.domain.DocExample;
import com.yyg.wiki.exception.BusinessException;
import com.yyg.wiki.exception.BusinessExceptionCode;
import com.yyg.wiki.mapper.ContentMapper;
import com.yyg.wiki.mapper.DocMapper;
import com.yyg.wiki.mapper.DocMapperCust;
import com.yyg.wiki.req.DocQueryReq;
import com.yyg.wiki.req.DocSaveReq;
import com.yyg.wiki.resp.DocQueryResp;
import com.yyg.wiki.resp.PageResp;
import com.yyg.wiki.util.CopyUtil;
import com.yyg.wiki.util.RedisUtil;
import com.yyg.wiki.util.RequestContext;
import com.yyg.wiki.util.SnowFlake;
import com.yyg.wiki.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

//import org.apache.rocketmq.spring.core.RocketMQTemplate;

/**
 * ClassName: DocService
 * Description:
 * date: 2021/7/22 15:00
 *
 * @author 17878
 * @since JDK 1.8
 */
@Service
public class DocService {
    @Resource
    private DocMapper docMapper;

//    @Resource
//    private RocketMQTemplate rocketMQTemplate;

    @Resource
    private ContentMapper contentMapper ;

    @Resource
    private DocMapperCust docMapperCust;

    @Resource
    private WsService wsService;
    @Resource
    private WebSocketServer webSocketServer;
    @Resource
    private SnowFlake snowFlake;

    @Resource
    private RedisUtil redisUtil;

    private static final Logger LOG = LoggerFactory.getLogger(DocService.class);
    public PageResp<DocQueryResp> list(DocQueryReq Req){
        PageHelper.startPage(Req.getPage(),Req.getSize());
        DocExample docExample = new DocExample();
        docExample.setOrderByClause("sort asc");
        DocExample.Criteria criteria = docExample.createCriteria();
        List<Doc> docList = docMapper.selectByExample(docExample);
        PageInfo<Doc> pageInfo = new PageInfo<>(docList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());
//        List<DocResp> respList=new ArrayList<>();
//        for (Doc doc : docList) {
//
//            DocResp docResp = CopyUtil.copy(doc, DocResp.class);
//            respList.add(docResp);
//        }
        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);
        return pageResp;
    }

    public List<DocQueryResp> all(Long ebookId){
        DocExample docExample = new DocExample();
        docExample.createCriteria().andEbookIdEqualTo(ebookId);
        docExample.setOrderByClause("sort asc");
        List<Doc> docList = docMapper.selectByExample(docExample);

        List<DocQueryResp> list = CopyUtil.copyList(docList, DocQueryResp.class);

        return list;
    }

    /**
     *
     * 功能描述:新增操作
     *
     * @param:
     * @return:
     * @auther: 17878
     * @date: 2021/7/29 15:14
     */
    @Transactional
    public void save(DocSaveReq req){
        System.out.println("genggaikkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk"+req);
        Doc doc=CopyUtil.copy(req,Doc.class);
        Content content=CopyUtil.copy(req, Content.class);
        if (ObjectUtils.isEmpty(req.getId())){
            doc.setId(snowFlake.nextId());
            doc.setViewCount(0);
            doc.setVoteCount(0);
            docMapper.insert(doc);

            content.setId(doc.getId());
            contentMapper.insert(content);
        }else {
            docMapper.updateByPrimaryKey(doc);
            int count=contentMapper.updateByPrimaryKeyWithBLOBs(content);
            if (count==0){
                contentMapper.insert(content);
            }
        }
    }

    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }
    public void delete(List<String> ids) {
        DocExample docExample = new DocExample();
        DocExample.Criteria criteria=docExample.createCriteria();
        criteria.andIdIn(ids);
        docMapper.deleteByExample(docExample);
    }

    public String findContent(Long id) {

        Content content=contentMapper.selectByPrimaryKey(id);
        docMapperCust.increaseViewCount(id);
        if (ObjectUtils.isEmpty(content)) {
            return "";
        } else {
            return content.getContent();
        }
    }
/**
 *
 * 功能描述:点赞，+推送消息
 *
 * @param:
 * @return:
 * @auther: 17878
 * @date: 2021/8/10 9:45
 */
    public void vote(Long id) {
        // docMapperCust.increaseVoteCount(id);
        // 远程IP+doc.id作为key，24小时内不能重复
        String ip = RequestContext.getRemoteAddr();
        if (redisUtil.validateRepeat("DOC_VOTE_" + id + "_" + ip, 5000)) {
            docMapperCust.increaseVoteCount(id);
        } else {
            throw new BusinessException(BusinessExceptionCode.VOTE_REPEAT);
        }

        //推送消息
        Doc docDb = docMapper.selectByPrimaryKey(id);
        String logId = MDC.get("LOG_ID");
//        rocketMQTemplate.convertAndSend("VOTE_TOPIC","【"+docDb.getName()+"】被点赞");
        wsService.sendInfo("【"+docDb.getName()+"】被点赞",logId);
    }


    public void updateEbookInfo() {
        docMapperCust.updateEbookInfo();
    }
}
